﻿using BlockOS.Server;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using UnityEngine;
using ZerAx.Net;

namespace BlockOS.Client
{
    public class LocalWorld : BaseWorld
    {
        private readonly ServerLocalProxy proxy;
        private InterThreadConnection local;

        private List<ChunkData> chunks = new();
        public LocalWorld()
        {
            proxy = new ServerLocalProxy();
            proxy.onReceiveMessage += Debug.Log;

            entityStorage = new EntityDataStorage(100);
        }

        public override IConnection GetConnection()
        {
            return local;
        }

        public override IEnumerator Init(Action<string> logger)
        {
            var (l, s) = InterThreadConnection.CreatePair();

            logger("Starting local server...");
            local = l;
            proxy.Start(new ServerConfig(Path.Combine(Application.persistentDataPath, "TestLevel")).WithName("Local"), server =>
            {
                server.AddConnection(s);
            });

            yield return base.Init(logger);
        }

        public void StartTcpListen(int port)
        {
            proxy.StartTcp(port);
        }

        public override void Deinit()
        {
            base.Deinit();
            proxy.RequestStop();
            proxy.Update();
        }

        public override void Update()
        {
            proxy.Update();
            base.Update();
        }
    }
}
